package com.example.singleReactorMultiThread;

import com.example.CommonMethod;
import lombok.Data;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Data
public class Handler implements Runnable {

    private Selector selector;
    private SocketChannel socketChannel;
    private SelectionKey selectionKey;
    private ExecutorService executorService;


    public Handler(SocketChannel socketChannel, Selector selector, ExecutorService executorService) {
        try {
            this.executorService = executorService;
            this.socketChannel = socketChannel;
            this.socketChannel.configureBlocking(false);
            this.selector = selector;
            this.socketChannel.register(this.selector, SelectionKey.OP_READ, this);
        } catch (Exception e) {

        }

    }

    @Override
    public void run() {
        if (selectionKey.isReadable()) {
            executorService.submit(()-> CommonMethod.read(selectionKey));
        } else if (selectionKey.isWritable()) {
            executorService.submit(()-> CommonMethod.write(selectionKey));
        }
    }


}
